package org.replay.config;

/*
 * Copyright © 2020 lizicong,All rights reserved.
 *
 * Licensed under the GPL License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import com.alibaba.fastjson.JSONObject;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * zk集群连接信息配置
 * 除了HOST外其它参数都不能上nacos，否则失效，原因不明
 * @author lizicong
 */
@Configuration
public class ZookeeperConnectionConfiguration {

    @Bean("zookeeperConnectionConfiguration-cfg")
    public JSONObject cfg(@Qualifier("nacos-cfg") JSONObject nacosConfiguration) {
        //截取相应的JSON配置信息中的节点
        return nacosConfiguration.getJSONObject("Zookeeper");
    }

    @Resource
    @Qualifier("zookeeperConnectionConfiguration-cfg")
    JSONObject cfg;

    /**
     * zk集群连接信息配置
     *
     * @return
     */
    @Bean
    public CuratorFramework getCuratorFramework() {
        //配置zk连接信息
        CuratorFramework cur = CuratorFrameworkFactory.builder()
                .connectString(cfg.getString("HOST"))
                //连接超时时间，临时节点过期时间就由此参数所定义(默认是60000)
                .sessionTimeoutMs(3000)
                //客户端连接zk的过程超时限制
                .connectionTimeoutMs(5000)
                //不知道是什么鬼休眠时间 和 最大重试数
                .retryPolicy(new ExponentialBackoffRetry(1000, 1))
                .build();
        //创建连接
        cur.start();
        return cur;
    }
}
